const jwt = require('jsonwebtoken');
const SECRET_KEY = 'your_secret_key';

// 验证 JWT
function authenticate(ctx, next) {
  const authHeader = ctx.headers.authorization; // 获取 Authorization 头
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    ctx.status = 401;
    ctx.body = 'Unauthorized: No token provided';
    return;
  }

  const token = authHeader.split(' ')[1]; // 提取 token
  try {
    ctx.state.user = jwt.verify(token, SECRET_KEY);
    return next();
  } catch (err) {
    ctx.status = 403;
    ctx.body = 'Forbidden: Invalid token';
  }
}



// 生成 JWT
function generateToken(user) {
  return jwt.sign({ id: user.id, loginName: user.login_name }, SECRET_KEY, { expiresIn: '1h' });
}

module.exports = { authenticate, generateToken };
